import {getDataByGet, getDataByPost} from '../util/getdata.util'
import router from "../router";
import {ElMessage} from "element-plus";
import {delLocalStorage, delSessionStorage, setLocalStorage, setSessionStorage} from "../util/storage.util";
import {LOGIN, LOGOUT} from "@/api/api";

export function loginUser(data: any) {
    getDataByPost(LOGIN, data, null)
        .then((res: any) => {
                console.log(res)
                console.log(res.message)
                console.log(res.datas.token)
                if (res.code == 200) {
                    // 用户数据存储
                    setLocalStorage("UserInfo", JSON.stringify(res.datas))
                    // localStorage
                    console.log("1")
                    setLocalStorage("Token", res.datas.token)
                    // sessionStorage
                    console.log("2")
                    setSessionStorage("Token", res.datas.token)
                    router.push('/')
                    ElMessage({
                        message: "登录成功",
                        type: "success",
                        duration: 2000
                    });
                }
            }
        )
        .catch((err: any) => {
                ElMessage({
                    message: "登录失败",
                    type: "error",
                    duration: 2000
                });
            }
        )
}

export function logoutUser(data: any) {
    getDataByGet(`${LOGOUT}?token=${data}`, null)
        .then((res: any) => {
                console.log(res.message)
                if (res.code == 200) {
                    delLocalStorage("UserInfo")
                    delLocalStorage("Token")
                    delSessionStorage("Token")
                    router.push('/login')
                    ElMessage({
                        message: "操作成功",
                        type: "success",
                        duration: 2000
                    });
                }
            }
        )
        .catch((err: any) => {
                ElMessage({
                    message: "操作失败",
                    type: "error",
                    duration: 2000
                });
            }
        )
}